package control;

import Util.PageUtil;
import bean.TInsect;
import com.google.gson.Gson;
import serves.Impl.insectSevImpl;
import serves.insectSev;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Statement;
import java.util.List;

@WebServlet(name = "insectServlet",urlPatterns = "/insect")
public class insectServlet extends HttpServlet {
    insectSev is = new insectSevImpl();
//    private static  int PAGESIZE=3;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String method = request.getParameter("method");
        if(method==null||method.equalsIgnoreCase("")){
            insectShow(request,response);

        }else if(method.equalsIgnoreCase("Add")){
            insectAdd(request,response);
        }
    }

    private void insectAdd(HttpServletRequest request, HttpServletResponse response){
        String insectName = request.getParameter("insectName");
        String host = request.getParameter("host");
        System.out.println("host = " + host);
        String mainDanger = request.getParameter("mainDanger");
        TInsect it = new TInsect();
        it.setInsect(insectName);
        it.setHost(host);
        it.setDanger(mainDanger);
        boolean flag= is.add(it);
        System.out.println("flag = " + flag);
    }

    private void insectShow(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        int pn =1;
        String pageNo = request.getParameter("pageNo");
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        if(pageNo==null){
            pn =1;
        }else{
            pn=Integer.parseInt(pageNo);
        }
        String insect = request.getParameter("insectName");
        System.out.println("insectName = " + insect);

        PageUtil<TInsect>insects = is.ListByPage(pn,pageSize,insect);
        Gson g = new Gson();
        String json =g.toJson(insects);
        System.out.println(json);
        pw.write(json);
    }
}
